#!/bin/sh

if [ "x$(echo ${PWD:0:1})" == "x/" ]; then
    BaseDir="$(dirname "${0}")"
else
    BaseDir="$(pwd)/$(dirname "${0}")"
fi

. "${BaseDir}/common.sh"

#  The logging routine
Log() {
	logger -p install.info -t 'Parallels Installer' "$@"
}

# Convert ISO to tarball
# $1 - path to ISO
# $2 - path to converted tarball
Iso2Tgz () {
    local iso_path=$1
    local tarball_path=$2
    local status=0

    # Create temporary mountpoint
    mount_point=`mktemp -d /tmp/iso2tgz.XXXXXX`
    if [ ! -d "$mount_point" ]; then
      Log "Iso2Tgz: cannot create temporary mountpoint ${mount_point}"
      return 1
    fi

    # Suspend 'CrossOver CD Helper' in order no to show
    # automaunt message box (bug #124850)
    killall -SIGSTOP 'CrossOver CD Helper'

    # Mount ISO to temporary mountpoint
    if hdiutil attach -nobrowse -mountpoint "${mount_point}" "${iso_path}"; then
        # Pack content of ISO
        if tar c -C "${mount_point}" ./ | gzip -1 > "${tarball_path}"; then
            # Unmount temporary mount point
            if ! hdiutil detach "${mount_point}"; then
		    Log "Iso2Tgz: cannot unmount ${mount_point}" && \
		    status=$(expr ${status} + 1)
            fi
        else
            Log "Iso2Tgz: cannot pack content of ${mount_point} to ${tarball_path}"
            status=$(expr ${status} + 1)
        fi
    else
        Log "Iso2Tgz: cannot mount ${iso_path} to ${mount_point}"
        status=$(expr ${status} + 1)
    fi

    # Reenable 'CrossOver CD Helper'
    killall -SIGCONT 'CrossOver CD Helper'

    # Remove temporary mount point
    rm -rf "${mount_point}"

    return ${status}
}

# Convert ISOs to tarballs
if [ -e "${TOOLS_DIR}/${iso}" ]; then
	Log "Converting ${iso} to ${iso%%.iso}.tar.gz"
	if ! Iso2Tgz "${TOOLS_DIR}/${iso}" "${TOOLS_DIR}/${iso%%.iso}.tar.gz"; then
		Log "Failed to convert ${iso} to ${iso%%.iso}.tar.gz"
	fi
else
	Log "File ${TOOLS_DIR}/${iso} is missing"
fi

# Copy receipts to Parallels Receipts directory
SWD=`cd "${0%/*}"; pwd`
. "${SWD}"/receipt.sh

# Just to finish installation with good mood
true
